package com.atguigu.datastream.day03;

import com.atguigu.datastream.bean.Event;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * ClassName: Flink_Source_Kafka
 * Package: com.atguigu.day03
 * Description:
 *                    RichFun
 * @Author ChenJun
 * @Create 2023/4/8 16:40
 * @Version 1.0
 */
public class Flink_12_Transformat_richFun {
    public static void main(String[] args) throws Exception {
        //1.获取Flink 流的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        // 2 . 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //TODO 将读进来的字符串转为Event
        SingleOutputStreamOperator<Event> map = streamSource.map(
                new MyRichMap()
//                new MapFunction<String, Event>() {
//            @Override
//            public Event map(String s) throws Exception {
//                String[] split = s.split(",");
//
//                return new Event(split[0], split[1], Long.parseLong(split[2]));
//            }
//        }
        );


        map.print();

        env.execute();
    }
    public static class MyRichMap extends RichMapFunction<String, Event> {
        /**
         * 生命周期方法初始化方法  比如创建链接
         * 在调用这个算子之前最先被调用
         * 在每个并行度上调用一次
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open..............");
            super.open(parameters);
        }

        /**
         * 生命周期方法 清理方法 比如释放资源
         * 在调用这个算子之后被调用
         * 在每个并行度上调用一次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close.............");
            super.close();
        }

        @Override
        public Event map(String s) throws Exception {
            String[] split = s.split(",");

                return new Event(split[0], split[1], Long.parseLong(split[2]));
        }
    }
}
